package com.shwread.android.newui.page;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.GlideUtil;
import com.NewActionHelp;
import com.google.gson.reflect.TypeToken;
import com.shwread.android.newui.activity.BookListWebActivity;
import com.shwread.android.newui.activity.BoutiqueActivity;
import com.shwread.android.newui.activity.CourseActivity;
import com.shwread.android.newui.adapter.EnterpriseAdapter;
import com.shwread.android.newui.adapter.SmartRecyclerAdapter;
import com.shwread.android.newui.adapter.TrainAdapter;
import com.shwread.android.newui.tools.DividerItemDecoration;
import com.shwread.android.newui.tools.FullyLinearLayoutManager;
import com.shwread.android.qysw.activity.CommonWebActivity;
import com.shwread.android.qysw.activity.GameWebActivity;
import com.shwread.android.qysw.activity.MainActivity;
import com.shwread.android.qysw10000229.R;
import com.shwread.android.ui.dialog.NoNetDialog;
import com.shwread.android.ui.page.AbstractUIPage;
import com.shwread.android.ui.page.BoutiquePage;
import com.shwread.android.ui.page.NewTrainingExamPage;
import com.shwread.android.ui.page.PersonalPage;
import com.shwread.android.ui.page.TrainingExamPage;
import com.shwread.android.ui.widget.refresh.PullToRefreshScrollView;
import com.shwread.android.ui.widget.refresh.base.PullToRefreshBase;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.tgx.tina.android.ipc.framework.IUIPage;

import org.apache.http.Header;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import base.tina.core.task.infc.ITaskResult;
import logic.bean.BannerInfo;
import logic.constants.DefaultConsts;
import logic.util.NetworkUtil;

/**
 * 学校项目，新的UI修改
 * Created by lex on 2017/7/6.
 */

public class TrainPage extends
        AbstractUIPage<MainActivity> implements View.OnClickListener {
    private static TrainPage instance;

    public static TrainPage getInstance(MainActivity t) {
        if (null == instance) {
            instance = new TrainPage(t);
        } else {
            instance.setActivity(t);
        }
        return instance;
    }

    public TrainPage(MainActivity t) {
        super(t);
    }

    private TextView tvTitle;
    private ImageView ivTrainHeader;
    private ImageView ivPersion;
    private LinearLayout llTrainBook, llTrainCourse;
    private RecyclerView recyclerView;
    private PullToRefreshScrollView refreshView;

    private View loadingView, freshView;
    private ImageView loadingImg;
    private AnimationDrawable animationDrawable;
    private List<BannerInfo> banners;
    private boolean isLastSuccess = false;
    private TrainAdapter adapter;

    private BannerInfo topBannerInfo = null;

    @Override
    public <E extends Activity> View createView(E arg0, int arg1) {
        if (null != curMyView) return curMyView;
        curMyView = bActivity.getLayoutInflater().inflate(R.layout.page_train, null);
        initView();
        return curMyView;
    }

    void initView() {
        banners = new ArrayList<>();
        tvTitle = (TextView) curMyView.findViewById(R.id.common_header_name);
        tvTitle.setText(bActivity.getResources().getString(R.string.main_tab_str2));
        ivPersion = (ImageView) curMyView.findViewById(R.id.common_header_persion);
        ivPersion.setVisibility(View.VISIBLE);
        ivPersion.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bActivity.goPersonalActivity();
            }
        });
        ivTrainHeader = (ImageView) curMyView.findViewById(R.id.ivTrainHeader);
        //根据屏幕的宽度，设置imageview的宽高，写固定值会出现拉伸变形
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) ivTrainHeader.getLayoutParams();
        lp.height = DefaultConsts.BANNER_DEFAULT_HIGHT;
        lp.width = DefaultConsts.BANNER_DEFAULT_WIDTH;
        ivTrainHeader.setLayoutParams(lp);
        llTrainBook = (LinearLayout) curMyView.findViewById(R.id.llTrainBook);
        llTrainCourse = (LinearLayout) curMyView.findViewById(R.id.llTrainCourse);
        recyclerView = (RecyclerView) curMyView.findViewById(R.id.lv);
        FullyLinearLayoutManager linearLayoutManager = new FullyLinearLayoutManager(bActivity);
        recyclerView.setNestedScrollingEnabled(false);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(linearLayoutManager);
        refreshView = (PullToRefreshScrollView) curMyView.findViewById(R.id.refreshView);

        loadingView = curMyView.findViewById(R.id.common_loading_layout);
        loadingImg = (ImageView) curMyView.findViewById(R.id.common_loading__img);
        freshView = curMyView.findViewById(R.id.refreshView);

        refreshView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ScrollView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
                if (refreshView.isHeaderShown()) { //下拉刷新
                    refresh();
                }
            }
        });

        llTrainBook.setOnClickListener(this);
        llTrainCourse.setOnClickListener(this);
    }

    private void refresh() {
        updateLoadingView(0);
        getViewPagerBanner();
    }

    @Override
    public int enter(IUIPage<?> arg0) {
        freshView.scrollTo(0, 0);
        if (!isLastSuccess) {
            if (NetworkUtil.isNetAvailable(bActivity)) {
                updateLoadingView(0);
                getViewPagerBanner();
            } else {
                new NoNetDialog(bActivity).show();
            }
        }
        return 0;
    }

    @Override
    public int leave(IUIPage<?> arg0) {
        return 0;
    }

    @Override
    public void notifyView(int arg0, Bundle arg1) {

    }

    @Override
    public void setStatus(int arg0) {

    }

    @Override
    public View updateView(int arg0, ITaskResult arg1) {
        return null;
    }

    public static void destroy() {
        if (instance != null) {
            instance.dispose();
            instance = null;
        }
    }

    @Override
    public void dispose() {
        isLastSuccess = false;
        if (null != banners) {
            banners.removeAll(banners);
        }
        super.dispose();
    }

    /**
     * @param flag 0:加载中，1：加载完成，-1：加载失败
     */
    private void updateLoadingView(int flag) {
        switch (flag) {
            case -1:
                loadingView.setVisibility(View.VISIBLE);
                freshView.setVisibility(View.GONE);
                if (animationDrawable != null && animationDrawable.isRunning()) {
                    animationDrawable.stop();
                }
                loadingImg.setBackgroundResource(R.drawable.home_loading_fail);
                break;
            case 0:
                loadingView.setVisibility(View.VISIBLE);
                freshView.setVisibility(View.GONE);
                loadingImg.setBackgroundResource(R.drawable.home_progress);
                animationDrawable = (AnimationDrawable) loadingImg.getBackground();
                animationDrawable.start();
                break;
            case 1:
                loadingView.setVisibility(View.GONE);
                freshView.setVisibility(View.VISIBLE);
                break;
        }
    }

    private void getViewPagerBanner() {
        NewActionHelp.qrySpecialInfoList(bActivity, new ObjectHttpResponseHandler<List<BannerInfo>>() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                Log.e("111111fail", "qrySpecialInfoList" + s);
                updateLoadingView(-1);
                refreshView.onRefreshComplete();
                isLastSuccess = false;
            }

            @Override
            public void onSuccess(int i, Header[] headers, List<BannerInfo> bannerInfos, String s) {
                Log.e("111111Success", "qrySpecialInfoList" + s);
                refreshView.onRefreshComplete();
                updateLoadingView(1);
                banners.clear();
                if (null == bannerInfos || bannerInfos.size() == 0) {
                    return;
                }
                topBannerInfo = bannerInfos.get(0);
                GlideUtil.load(bActivity, appendBannerUrl(topBannerInfo.getImgUrl()), ivTrainHeader);
                ivTrainHeader.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        switch (topBannerInfo.getType()) {
                            case BannerInfo.TYPE_BANNER:
                                break;
                            case BannerInfo.TYPE_BOOKS:
                                break;
                            case BannerInfo.TYPE_BOOKSURL:
                                bActivity.goBookDetailActivity(topBannerInfo.getBooks());
                                break;
                            case BannerInfo.TYPE_URL:
                                Intent webIntent = new Intent(bActivity, BookListWebActivity.class);
                                webIntent.putExtra(DefaultConsts.title_s, topBannerInfo.getBannerName());
                                webIntent.putExtra(DefaultConsts.req_url_s, topBannerInfo.getContent());
                                webIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                                bActivity.startActivity(webIntent);
//                                bActivity.goWebViewActivity(topBannerInfo);
                                break;
                        }
                    }
                });
                if (bannerInfos.size() > 1) {
                    bannerInfos.remove(0);
                    banners.addAll(bannerInfos);
                    adapter = new TrainAdapter(bActivity, banners);
//                    SmartRecyclerAdapter smartRecyclerAdapter = new SmartRecyclerAdapter(adapter);
                    adapter.setOnRecyclerViewItemClickListener(new TrainAdapter.OnRecyclerViewItemClickListener() {
                        @Override
                        public void onItemClick(View view, Object data) {
                            Toast.makeText(bActivity, data.toString(), Toast.LENGTH_SHORT).show();
                        }
                    });
                    recyclerView.setAdapter(adapter);
                    adapter.setOnRecyclerViewItemClickListener(new TrainAdapter.OnRecyclerViewItemClickListener() {
                        @Override
                        public void onItemClick(View view, Object data) {
                            BannerInfo bannerInfo = (BannerInfo) data;
                            switch (bannerInfo.getType()) {
                                case BannerInfo.TYPE_BANNER:
                                    break;
                                case BannerInfo.TYPE_BOOKS:
                                    break;
                                case BannerInfo.TYPE_BOOKSURL:
                                    bActivity.goBookDetailActivity(bannerInfo.getBooks());
                                    break;
                                case BannerInfo.TYPE_URL:
                                    Intent webIntent = new Intent(bActivity, BookListWebActivity.class);
                                    webIntent.putExtra(DefaultConsts.title_s, bannerInfo.getBannerName());
                                    webIntent.putExtra(DefaultConsts.req_url_s, bannerInfo.getContent());
                                    webIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                                    bActivity.startActivity(webIntent);

                                    break;
                            }
                        }
                    });
                }
            }

            @Override
            public Type getType() {
                return new TypeToken<List<BannerInfo>>() {
                }.getType();
            }
        });
    }

    private String appendBannerUrl(String imgUrl) {
        StringBuffer sb = new StringBuffer(imgUrl);
        sb.append("?c=0&w=");
        sb.append(DefaultConsts.BANNER_DEFAULT_WIDTH);
        sb.append("&h=");
        sb.append(DefaultConsts.BANNER_DEFAULT_HIGHT);
        sb.append("&p=0");
        return sb.toString();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.llTrainBook:
//                bActivity.changePage(NewBoutiquePage.getInstance(bActivity), DEFAULT_STATUS);
                bActivity.startActivity(new Intent(bActivity, BoutiqueActivity.class));
                break;
            case R.id.llTrainCourse:
//                bActivity.changePage(new NewTrainingExamPage(bActivity), DEFAULT_STATUS);
                bActivity.startActivity(new Intent(bActivity, CourseActivity.class));
                break;
        }
    }

}
